package com.sc.service.order;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sc.dal.dto.order.OrderDetailDto;
import com.sc.dal.dto.order.TCustomer;
import com.sc.dal.dto.order.TDataSource;
import com.sc.dal.dto.order.TInventory;
import com.sc.dal.dto.order.TSaleOrder;
import com.sc.dal.dto.order.TSaleOrderDetails;
import com.sc.dal.dto.order.TSaleOrderDto;
import com.sc.dal.dto.order.TSaleOrderInsertDto;
import com.sc.dal.dto.order.TSaleOrderInsertResult;
import com.sc.dal.dto.order.TSaleOrderResult;
import com.sc.dal.dto.order.TUnit;
import com.sc.dal.dto.promotion.PromotionDetailDto;
import com.sc.dal.mapper.order.ExpressMapper;
import com.sc.dal.mapper.order.OrderDetailMapper;
import com.sc.dal.mapper.order.OrderMapper;
import com.sc.dal.mapper.order.OrderPaymentMapper;
import com.sc.dal.mapper.order.OrderShipMapper;
import com.sc.dal.mapper.seller.SellerMapper;
import com.sc.dal.model.goods.Goods;
import com.sc.dal.model.goods.GoodsStock;
import com.sc.dal.model.member.MemberNews;
import com.sc.dal.model.order.Express;
import com.sc.dal.model.order.Order;
import com.sc.dal.model.order.OrderDetail;
import com.sc.dal.model.order.OrderPayment;
import com.sc.dal.model.order.OrderShip;
import com.sc.dal.model.order.Orders;
import com.sc.dal.model.order.Products;
import com.sc.dal.model.order.Shop;
import com.sc.dal.model.seller.Seller;
import com.sc.service.BaseServiceImpl;
import com.sc.service.consultComment.ConsultCommentService;
import com.sc.service.goods.GoodsService;
import com.sc.service.goods.GoodsSkuService;
import com.sc.service.member.MemberNewsService;
import com.sc.service.promotion.PromotionService;
import com.sc.util.data.Arith;
import com.sc.util.data.Common;
import com.sc.util.data.Constants;
import com.sc.util.data.DateUtil;
import com.sc.util.openAPI.TOpenAPIUtil;

/**
 * @ClassName: OrderService
 * @Description: 处理订单业务逻辑层
 * @author LeiJia
 * @date 2017年3月14日 上午10:12:26
 * @version V1.0
 */
@Service
public class OrderService extends  BaseServiceImpl<Orders> {
	  @Autowired
      private OrderMapper orderMapper;
	  
	  @Autowired
	  private OrderDetailMapper orderDetailMapper;
	  
	  @Autowired
	  private OrderShipMapper  orderShipMapper;
	  
	  @Autowired
	  private OrderPaymentMapper  orderPaymentMapper;	  
	  
	  @Autowired
	  private ExpressMapper expressMapper;
	  
	  @Autowired
	  private SellerMapper sellerMapper;
	  
	  @Autowired
	  private MemberNewsService memberNewsService;
	  
	  @Autowired
	  private GoodsService goodsService;
	  
	  @Autowired
	  private GoodsSkuService goodsSkuService;	  

	  @Autowired
	  private ConsultCommentService  consultCommentService;
	  
	  @Autowired
	  private PromotionService promotionService;
	  
	  public Order selectOrderByOrderId(String orderId){
		  return orderMapper.selectOrderByOrderId(orderId);
	  }
	  
	  public List<OrderDetail> selectOrderDetailList(String orderId){
		  return orderDetailMapper.selectListByOrderId(orderId);
	  }	  
	  
	  public List<Orders> selectList(Map<String,Object> paramMap){
		  return orderMapper.selectList(paramMap);
	  }
	  
	  public int counts(Orders orders){
		  return orderMapper.counts(orders);
	  }
	  public List<Express> selectByParam(){
		  return expressMapper.selectByParam();
	  }
	  
	  public Express selectByExpressById(Integer id){
		  return expressMapper.selectByPrimaryKey(id);
	  }
	  
	  
	  public int insert(Order order){
		return   orderMapper.insert(order);
	  }
	  
	  public int insert(OrderDetail orderDetail ){
		  return  orderDetailMapper.insert(orderDetail);
	  }
	  
	  public int insert(OrderShip orderShip ){
		  return  orderShipMapper.insert(orderShip);
	  }
	  
	  public int insert(OrderPayment orderPayment ){
		  return  orderPaymentMapper.insert(orderPayment);
	  }
	  
	  public int updateOrder(Order order){
		  return orderMapper.updateByPrimaryKeySelective(order);
	  }
	  
	  public int updateOrderDetail(OrderDetail detail){
		  return orderDetailMapper.updateByPrimaryKeySelective(detail);
	  }
	  
	  public Order selectByPrimaryKey(String orderId){
		  return orderMapper.selectByPrimaryKey(orderId);
	  }
	  
	  public List<OrderPayment> selectByPayments(OrderPayment payment){		   
		  return orderPaymentMapper.selectOrderPayments(payment);
	  }
	 
	  public List<Products>  selectOrderProductsByOrderId(String orderId,String goodsId){
		  Products product = new Products();
		  product.setOrderId(orderId);
		  product.setProductId(new Integer(goodsId));
		  return orderMapper.selectOrderProductsByOrderId(product);
	  }
	  public List<Products>  selectOrderProductsByOrderId(String orderId){
		  Products product = new Products();
		  product.setOrderId(orderId);
		  return orderMapper.selectOrderProductsByOrderId(product);
	  }
	  
	  public List<Products>  selectOrderProductsByProducts(Products product){
		  return orderMapper.selectOrderProductsByOrderId(product);
	  }

	  public int updateOrderPayment(OrderPayment payment) {
			return orderPaymentMapper.updateByPrimaryKey(payment);
	  }

	 public OrderDetailDto selectOrderDetailByOrderId(String orderId) {
			 return orderMapper.selectOrderDetailByOrderId(orderId);
	 } 
	 
	 public List<Orders>  selectByParam(Orders order){
		 return orderMapper.selectByParam(order);
	 }
	 
	/**
	 * @Title: insertMemberNews
	 * @Description 生成一条交易物流消息通知
     * @param news
	 * @date 2017年4月17日下午 17:19
	 * @author LeiJia  
	 * @return 
	 */
	public int  insertMemberNews(MemberNews news){
		String orderId = news.getOrderId();
		//查找订单中的第一个商品
		OrderDetailDto dto = selectOrderDetailByOrderId(orderId);
		if(dto !=null){
			List<Products> products = dto.getProducts();
			if(products != null && products.size() >0){
				news.setNewsContent(news.getNewsTitle()+"！你购买的["+products.get(0).getProductName()+"]"+news.getNewsTitle());
			}
		}
		news.setType(Constants.MemberNews.NEWS_TYPEA);
		news.setTypeTitle(Constants.MemberNews.NEWS_TYPE_TITLEA);
    	news.setIsDelete(Constants.IS_DELETEA);
    	return memberNewsService.insertMemberNews(news);
	}

	/**
	 * @Title: addOrderToTSaleOrder
	 * @Description 向T+系统添加一条销售订单
     * @param news
	 * @date 2017年4月17日下午 17:19
	 * @author LeiJia  
	 * @return 
	 */
	public TSaleOrderInsertResult addOrderToTSaleOrder(Order order) {
		try{

			//向T+系统查找该该订单是否已经添加过
			TSaleOrderResult  result = TOpenAPIUtil.getTSaleOrderByExternalCode(order.getOrderId(),true);
			if(result != null && result.getRows() != null && result.getRows().size() > 0){
				 List<TSaleOrder> saleOrderList = result.getRows();
				 for(TSaleOrder saleOrder:saleOrderList){
					 if(saleOrder.getExternalCode().equals(order.getOrderId())){
						 updateUploadTOrderStatus(order.getOrderId(), Constants.TConstants.UPLOADED_TORDER_STATUS_B);
						 break;
					 }
				 }
			}
			
		    OrderShip orderShip = orderShipMapper.selectOrderShipByOrderId(order.getOrderId()) ;
			//向T+新增一个订单
			TSaleOrderInsertDto dto = new TSaleOrderInsertDto();
			TSaleOrderDto saleOrderDto = new TSaleOrderDto();
			saleOrderDto.setVoucherDate(DateUtil.dateToString2(order.getCreateDate()));	//可以不要
			saleOrderDto.setAddress(orderShip.getShipAddress());
			saleOrderDto.setContactPhone(orderShip.getTel());saleOrderDto.setExternalCode(order.getOrderId());
			TCustomer customer = new TCustomer();
			customer.setCode(Constants.T_CUSTOMER_CODE);
			saleOrderDto.setCustomer(customer);
			Object[] dynamicPropertyKeys = {};
			saleOrderDto.setDynamicPropertyKeys(dynamicPropertyKeys);
			Object[] dynamicPropertyValues = {};
			saleOrderDto.setDynamicPropertyValues(dynamicPropertyValues);
			saleOrderDto.setExternalCode(order.getOrderId());
			saleOrderDto.setLinkMan(orderShip.getShipName());
			saleOrderDto.setMemo(order.getMemberId());
			saleOrderDto.setIsAutoAudit(false); //为True时，生成到T+中的销售订单自动进行审核，审核人与制单人相同，不判断审核权限为Flase时。不进行自动审核
			TDataSource dataSource = new TDataSource();
			dataSource.setCode(Constants.TdataSource.T_DATASOURCE_B2B);
			saleOrderDto.setDataSource(dataSource);
			List<TSaleOrderDetails> saleOrderDetails = new ArrayList<TSaleOrderDetails>();
			List<OrderDetail> orderDetails = orderDetailMapper.selectListByOrderId(order.getOrderId());
		   
			for(OrderDetail detail :orderDetails){
				TSaleOrderDetails orderDetail = new TSaleOrderDetails();
				Object[] dynamicPropertyKeys_ = {};
				Object[] dynamicPropertyValues_ = {};
				orderDetail.setDynamicPropertyKeys(dynamicPropertyKeys_);
				orderDetail.setDynamicPropertyValues(dynamicPropertyValues_);
				orderDetail.setOrigPrice(detail.getMarketPrice());
				orderDetail.setOrigTaxAmount(new BigDecimal(orderDetailProMoney(order,detail,orderDetails.size()).get(detail.getId()).toString()));
				orderDetail.setQuantity(detail.getNumber());
				orderDetail.setIsPresent(false);//需要查询是否为赠品
				TInventory tInventory = new TInventory();
				Integer prdouctId = detail.getProductId();
				Goods goods =goodsService.selectByPrimaryKey(prdouctId);
				tInventory.setCode(goods.getCode());
				orderDetail.setInventory(tInventory);
				TUnit unit =new TUnit();
				unit.setName(goods.getUnitName());
				orderDetail.setUnit(unit);
				saleOrderDetails.add(orderDetail);
			}
			saleOrderDto.setSaleOrderDetails(saleOrderDetails);
			dto.setDto(saleOrderDto);
			TSaleOrderInsertResult results =TOpenAPIUtil.insertOrderToTSaleOrder(dto,true);//非定时器处理
			//updateGoodsStock(order); //减少库存
			//向T+系统查找该该订单是否已经添加过
			TSaleOrderResult tSaleOrderResult = TOpenAPIUtil.getTSaleOrderByExternalCode(order.getOrderId(),true);//非定时器处理
			if(tSaleOrderResult != null && tSaleOrderResult.getRows() != null && tSaleOrderResult.getRows().size() == 1) {
				 updateUploadTOrderStatus(order.getOrderId(), Constants.TConstants.UPLOADED_TORDER_STATUS_B);
			}
			return 	results;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	//计算订单中每个商品的优惠价格
	public Map<Integer, Object> orderDetailProMoney(Order order,OrderDetail detail,int detailSize) {
		Integer goodsId = detail.getProductId();
		Map<Integer, Object> resultMap = new LinkedHashMap<Integer, Object>();
		Double pmtGoodsMoney = order.getPmtGoods();
		Double pmtOrderMoney = order.getPmtOrder();
		BigDecimal divPmtMoney = new BigDecimal(0);
		// 参与促销的商品
		String proType = order.getProType();
		String[] proGoodsIdArry = {};
		String[] proDetailArry = {};

		
		//计算运费 均摊到每个订单详情上
		//BigDecimal expressFee = order.getShipMoney(); 
		BigDecimal expressFee = new BigDecimal(0); //2017-07-07 17:19 毛经理争取唐总建议暂时不传运费到T+
		expressFee = Arith.div(expressFee, new BigDecimal(detailSize),2);
		if(Common.isNotEmpty(proType)){

			if (proType.equals(Constants.OrdersPromotion.ORDER_SALE_PROMOTION_TYPE_B)) {

				if (pmtGoodsMoney != null) {
					divPmtMoney = Arith.div(new BigDecimal(pmtGoodsMoney), new BigDecimal(detailSize),2);
					divPmtMoney = Arith.add(divPmtMoney, expressFee);
				}
				if (pmtOrderMoney != null) {
					divPmtMoney = Arith.div(new BigDecimal(pmtOrderMoney), new BigDecimal(detailSize),2);
					divPmtMoney = Arith.add(divPmtMoney, expressFee);
				}
				resultMap.put(detail.getId(), Arith.sub(Arith.mul(detail.getMarketPrice(), new BigDecimal(detail.getNumber())), divPmtMoney).setScale(2, BigDecimal.ROUND_HALF_UP));
				return resultMap;
			} else if (proType.equals(Constants.OrdersPromotion.ORDER_SALE_PROMOTION_TYPE_A)) {
				String proGoodsStr = order.getProGoods();
				proGoodsIdArry = proGoodsStr.split(",");
				String proDetailIdStr = order.getProDetailId();
				proDetailArry = proDetailIdStr.split(",");
				for (int i = 0; i < proGoodsIdArry.length; i++) {
	                if(proGoodsIdArry[i].equals(goodsId.toString())){
	                	PromotionDetailDto proDetail =  promotionService.selectProDetailByPrimaryKey(Integer.valueOf(proDetailArry[i]));
	                	switch(proDetail.getPro_type()){
	    				case "0": //订单满减
	    					if(Common.isNotEmpty(proDetail.getPro_money())){
	    						BigDecimal total = Arith.sub(Arith.mul(detail.getMarketPrice(), new BigDecimal(detail.getNumber())), new BigDecimal(proDetail.getPro_money().split(":")[1])).setScale(2, BigDecimal.ROUND_HALF_UP) ;
	    						total = Arith.add(total, expressFee);
	    						resultMap.put(detail.getId(),total);
	    					}
	    					break;
	    				case "1": //商品满减
	    					if(Common.isNotEmpty(proDetail.getPro_money())){
	    						BigDecimal total = Arith.sub(Arith.mul(detail.getMarketPrice(), new BigDecimal(detail.getNumber())), new BigDecimal(proDetail.getPro_money().split(":")[1])).setScale(2, BigDecimal.ROUND_HALF_UP) ;
	    						total = Arith.add(total, expressFee);
	    						resultMap.put(detail.getId(),total);
	        					
	    					}
	    					break;
	    				case "2": //商品满赠
	    					if(Common.isNotEmpty(proDetail.getPro_money())){
	    						BigDecimal total = new BigDecimal(0);
	    						total = Arith.add(total, expressFee);
	    						resultMap.put(detail.getId(), total);
	    					}
	    					break;
	    				case "3":  //商品打折
	    					if(Common.isNotEmpty(proDetail.getPro_count())){
	    						BigDecimal rate = new BigDecimal(new Double(proDetail.getPro_rate())/100).setScale(2, BigDecimal.ROUND_HALF_UP);   


	    						BigDecimal total =Arith.mul(Arith.mul(detail.getMarketPrice(), new BigDecimal(detail.getNumber())), rate).setScale(2, BigDecimal.ROUND_HALF_UP) ;
	    						total = Arith.add(total, expressFee);
	    						resultMap.put(detail.getId(),total);
	        					
	    					}
	    					break;
	    			}
	                }else{
	        			resultMap.put(detail.getId(), Arith.add(Arith.mul(detail.getMarketPrice(), new BigDecimal(detail.getNumber())), expressFee).setScale(2, BigDecimal.ROUND_HALF_UP));	
	        			return resultMap;
	        		}
				}
			}else{
				resultMap.put(detail.getId(), Arith.add(Arith.mul(detail.getMarketPrice(), new BigDecimal(detail.getNumber())), expressFee).setScale(2, BigDecimal.ROUND_HALF_UP));	
				return resultMap;
			}
		}else{
			resultMap.put(detail.getId(), Arith.add(Arith.mul(detail.getMarketPrice(), new BigDecimal(detail.getNumber())), expressFee).setScale(2, BigDecimal.ROUND_HALF_UP));	
			return resultMap;
		}
		return resultMap;
	}
	//根据店铺ID查找店铺名称
	public Seller getSellerById(Integer sellerId){
		return sellerMapper.selectByPrimaryKey(sellerId);
	}
	
	public List<Order> selectShouldCancelOrders(){
		return orderMapper.selectShouldCancelOrders();
	}

	//计算店铺的商品总数，商品总金额
	public Shop getShop(Shop shop,String memberId){
		List<Products> products = shop.getProducts();
		int $itemnum = 0;
		BigDecimal $totalAmount =new BigDecimal(0);
		for(Products product:products){
			Goods goods = goodsService.selectByPrimaryKey(product.getProductId());
			product.setMarketPrice(goods.getMarketPrice());
			product = goodsService.discoutProducts(product,memberId);
			$itemnum += product.getQuantity();
			if(product.getDiscountMarketPrice() != null){
                BigDecimal $total = Arith.mul(product.getDiscountMarketPrice(), new BigDecimal(product.getQuantity())).setScale(2, BigDecimal.ROUND_HALF_UP);
                $totalAmount = Arith.add($totalAmount,$total).setScale(2, BigDecimal.ROUND_HALF_UP);
			}else{
                BigDecimal $total = Arith.mul(goods.getMarketPrice(), new BigDecimal(product.getQuantity())).setScale(2, BigDecimal.ROUND_HALF_UP);
                $totalAmount = Arith.add($totalAmount,$total).setScale(2, BigDecimal.ROUND_HALF_UP);;
			}
		}
		shop.setItemnum($itemnum);
		shop.setTotalAmount($totalAmount);
		return shop;
	}

	  //减少商品对应的的规格库存数量
	public void  updateGoodsStock(Order order_){
		List<Products>  products = selectOrderProductsByOrderId(order_.getOrderId());
		for(Products product :products){

			String[] goods_sku_ids = {};
			if(Common.isNotEmpty(product.getGoods_sku_id())){
				goods_sku_ids =product.getGoods_sku_id().split(",");
			}
			String goods_sku_values="";
			if(goods_sku_ids.length > 0){
				for(String sku_id: goods_sku_ids){
					Map<String,Object> paramMap = new LinkedHashMap<String, Object>();	
					paramMap.put("goods_sku_id", sku_id);
					paramMap = goodsSkuService.selectGoodsSkuById(paramMap);
					if(paramMap != null && paramMap.size() > 0){
						goods_sku_values += paramMap.get("base_sku_name").toString() +":"+ paramMap.get("base_sku_value_name").toString() +",";
					}
				}
			}
			  //减少商品对应的的规格库存数量9
		    GoodsStock stock = new GoodsStock();
		    if(Common.isNotEmpty(goods_sku_values)){
			     stock = goodsService.getGoodsStock(stock, goods_sku_values.split(","));
		    }
			stock.setGoodsId(product.getProductId());
		    stock.setSaleBaseQuantity(Integer.valueOf((product.getQuantity())));
			int updateGoodsStockResult = goodsService.updateGoodsStock(stock);
			if(updateGoodsStockResult  <= 0){
			/*	DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_STOCK_UPDATE_ERROR);
				return resultMap;*/
				System.out.println("商品id为：" + product.getProductId() + " 规格信息为："+ product.getGoods_sku_id() +  " 库存修改失败！");
			}else{
				System.out.println("商品id为：" + product.getProductId() + " 规格信息为："+ product.getGoods_sku_id() +  " 库存修改成功！");
			}
		}
      }
	

	
	//修改评论成功的订单与订单详细评论状态
	public void updateOrderAndOrderDetailCommentStatus(String orderId,Integer goodsId){

		Order order = new Order();
		order.setOrderId(orderId);
	    com.sc.dal.model.order.OrderDetail detail = new com.sc.dal.model.order.OrderDetail();
	    detail.setOrderId(orderId);
	    detail.setProductId(goodsId);
	    detail.setIsComment(Constants.OrderDetail.OrderStatus.IS_COMMENTB);
		updateOrderDetail(detail); //修改订单详细评论状态		
		

		Products product = new Products();
		product.setOrderId(orderId);
		List<Products> productsList = selectOrderProductsByProducts(product); //查询订单中的全部商品
		product.setIsComment(Constants.OrderDetail.OrderStatus.IS_COMMENTA);
		List<Products> products = selectOrderProductsByProducts(product); //待评论的订单详细商品
		
		List<Products> noAddCommentProducts = new ArrayList<Products>(); //记录未追评的商品
		for(int i =0; i < productsList.size();i++){
            Products p = productsList.get(i);
			//查寻当前商品评论的次数
			List<String> countList = consultCommentService.findIsComment(orderId,p.getProductId());
			if(countList!=null && Integer.valueOf(countList.get(0) )<2 ){
				noAddCommentProducts.add(p);
			}
		}
		
		if(products.size() == 0 && noAddCommentProducts.size() == 0){
			order.setIsComment(Constants.OrderDetail.OrderStatus.IS_COMMENTB);
			order.setIsDelete(Constants.IS_DELETEA);
			updateOrder(order); 
			// 修改订单评论状态
		}
	}
	
	//记录订单是否上传T+
	public void updateUploadTOrderStatus(String orderId,String uploadTOrderStatus){
		 Order o = new Order();
		 o.setUploadedTOrder(uploadTOrderStatus);
		 o.setOrderId(orderId);
		 updateOrder(o);
	}
}
